unit mapplaceselectionunit;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons,
  maplistframeunit, mapviewframeunit, database, tilesetgraphicsunit, fpjson;

type

  { TMapPlaceSelectionForm }

  TMapPlaceSelectionForm = class(TForm)
    EcCancelBitBtn: TBitBtn;
    EcOkBitBtn: TBitBtn;
    EcResultLineBevel: TBevel;
    EcResultPanel: TPanel;
    ContentPanel: TPanel;
    SelectMapViewFrame: TMapViewFrame;
    SelectedMapListFrame: TMapListFrame;
    MapListMapSplitter: TSplitter;
  private
    FSelectedMapId: Integer;
    FSelectedX: Integer;
    FSelectedY: Integer;
    FTilesetGraphics: TTilesetGraphics;
    FDb: TDatabase;
    FMap: TJSONObject;

    procedure Init;
    procedure FreeTemporaryObjects;
    procedure MapSelectionChanged(AMapId: Integer);
    procedure SelectMapViewFrameDoubleClick;
  public
    property SelectedX: Integer read FSelectedX;
    property SelectedY: Integer read FSelectedY;
    property SelectedMapId: Integer read FSelectedMapId;
    function ShowSelection(MapId, X, Y: Integer; Db: TDatabase): Boolean;
    destructor Destroy; override;
  end;

var
  MapPlaceSelectionForm: TMapPlaceSelectionForm;

implementation


uses
  globals, constants;

{$R *.lfm}

{ TMapPlaceSelectionForm }

procedure TMapPlaceSelectionForm.Init;
begin
  SelectedMapListFrame.SelectionChangedCallback := @MapSelectionChanged;
  SelectedMapListFrame.FillMapInfoList;
  SelectMapViewFrame.Mode := mvfmSelectLocation;
  SelectMapViewFrame.OnDoubleClick := @SelectMapViewFrameDoubleClick;
  FTilesetGraphics := TTilesetGraphics.Create;
end;

procedure TMapPlaceSelectionForm.FreeTemporaryObjects;
begin
  if FTilesetGraphics <> nil then
    FreeAndNil(FTilesetGraphics);
  if FMap <> nil then
    FreeAndNil(FMap);
end;

procedure TMapPlaceSelectionForm.MapSelectionChanged(AMapId: Integer);
begin
  if AMapId > 0 then begin
    if FMap <> nil then
      FreeAndNil(FMap);

    FSelectedMapId := AMapId;
    FMap := Game.LoadMap(AMapId);

    FTilesetGraphics.SetTileset(FDb.Tilesets.Objects[FMap.Integers['tilesetId']]);
  end else begin
    FTilesetGraphics.SetTileset(nil);
    FSelectedMapId := 0;
  end;

  SelectMapViewFrame.SetMap(FMap, FTilesetGraphics, FDb);
end;

procedure TMapPlaceSelectionForm.SelectMapViewFrameDoubleClick;
begin
  EcOkBitBtn.Click;
end;

function TMapPlaceSelectionForm.ShowSelection(MapId, X, Y: Integer; Db: TDatabase): Boolean;
begin
  FDb := Db;
  Init;
  SelectedMapListFrame.SelectMapById(MapId);
  with SelectMapViewFrame do begin
    EventCursorX := X;
    EventCursorY := Y;
  end;

  ShowModal;

  FSelectedX := SelectMapViewFrame.EventCursorX;
  FSelectedY := SelectMapViewFrame.EventCursorY;

  ShowSelection := ModalResult = mrOK;
  SelectedMapListFrame.ClearList;
  SelectMapViewFrame.SetMap(nil, nil, nil);
  FreeTemporaryObjects;
end;

destructor TMapPlaceSelectionForm.Destroy;
begin
  FreeTemporaryObjects;
  inherited Destroy;
end;

end.

